import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:im_base/public/components/avatar_widgets.dart';
import 'package:im_base/public/global/global.dart';
import 'package:im_base/public/service/tim_service.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:im_base/public/ext/string_ext.dart';

///会话列表 item
class ConversationItem extends StatelessWidget {
  final V2TimConversation itemData;
  final Function(String, String, bool) conversationClick;
  final Function(String)? deleteItem;

  ConversationItem(
      {required this.itemData,
      required this.conversationClick,
      this.deleteItem,
      Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return itemData.conversationID.isEmpty ? Container() : getItem(context);
  }

  ///会话列表 item UI
  Widget getItem(context) {
    return InkWell(
      onTap: () {
        markAsRead(itemData);
        conversationClick(
            itemData.showName!,
            itemData.userID.isNullEmpty()
                ? itemData.groupID!
                : itemData.userID!,
            itemData.userID.isNullEmpty());
      },
      child: Slidable(
        child: Container(
          margin: EdgeInsets.only(left: 16, top: 2),
          height: 70,
          width: double.infinity,
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(color: Color(0xFFE0E0E0), width: 1))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Avatar(
                size: 35,
                backgroundImage: itemData.faceUrl.isNullEmpty()
                    ? null
                    : NetworkImage(itemData.faceUrl!),
                shape: itemData.userID.isNullEmpty()
                    ? AvatarShape.standard
                    : AvatarShape.circle,
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 12),
                  padding: EdgeInsets.only(bottom: 4, top: 2),
                  height: double.infinity,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      getName(itemData.showName!),
                      getMsg(itemData.lastMessage)
                    ],
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.only(right: 12, top: 10, bottom: 8),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    getData(itemData.lastMessage!.timestamp!),
                    getUnread(itemData.unreadCount ?? 0)
                  ],
                ),
              )
            ],
          ),
        ),
        actionPane: SlidableDrawerActionPane(),
        secondaryActions: actionsView(),
        actionExtentRatio: 0.2,
      ),
    );
  }

  List<Widget> actionsView() {
    return [
      SlideAction(
        child: Text(
          '删除',
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
        color: Colors.red,
        onTap: () {
          deleteItem?.call(itemData.conversationID);
        },
      ),
      SlideAction(
        child: Text(
          '已读',
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
        color: Colors.blue,
        onTap: () => markAsRead(itemData),
      ),
    ];
  }
}

///进入聊天页面将该会话标记为已读
void markAsRead(itemData) {
  TimService.instance.markMessageRead(itemData);
}

///未读消息数量展示
getUnread(int unreadCount) {
  return unreadCount > 0
      ? Container(
          padding: EdgeInsets.all(2),
          width: 18,
          height: 18,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.red, borderRadius: BorderRadius.circular(9)),
          child: Text(
            unreadCount > 99 ? '···' : unreadCount.toString(),
            style: TextStyle(
                color: Colors.white, fontSize: unreadCount > 99 ? 12 : 10),
          ),
        )
      : Container();
}

///时间展示
getData(int timestamp) {
  return Text(
    formatTime(timestamp),
    style: TextStyle(color: Color(0xFF616161), fontSize: 14),
  );
}

///最后一条消息信息展示
Widget getMsg(V2TimMessage? lastMessage) {
  return getText(
    lastMessage == null ? '问诊消息' : getLastMsg(lastMessage)!,
  );
}

///用户名字
Widget getName(String showName) {
  return Text(
    showName,
    maxLines: 1,
    style: TextStyle(color: Colors.black87, fontSize: 16),
  );
}

///因为emoji也是text类型,所以这里需要做对应的判断
Widget getText(String text) {
  String regex = "\\[(\\S+?)\\]";
  if (RegExp(regex).hasMatch(text)) {
    final group = RegExp(regex).allMatches(text);
    List<InlineSpan> spans = List.empty(growable: true);
    int start = 0; //记录当前emoji起始位置
    group.forEach((element) {
      final subText = text.substring(start, element.start);
      start = element.end;
      if (!subText.isNullEmpty()) {
        spans.add(TextSpan(
            text: subText,
            style: TextStyle(color: Colors.black87, fontSize: 14)));
      }
      spans.add(WidgetSpan(
          child: Image.asset(
        '${Global.EMOJI_PATH}${element.group(0)}@2x.png',
        width: 18,
        height: 18,
      )));
    });
    return Text.rich(
      TextSpan(children: spans),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  } else {
    return Text(
      text,
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
      style: TextStyle(color: Color(0xFF616161), fontSize: 14),
    );
  }
}
